define(function (require) {
	var app = require('app')
    .controller('metadataCtrl', ['$scope','$rootScope', function($scope,$rootScope){

    	$scope.metaId = null;

    	$scope.setMeta = function(fn,name){
    		$rootScope[fn].defaultQueryObject.mid=name;
            $rootScope[fn].queryObject={};
            $rootScope.loadData(fn);
            $scope.metaId = name;
    	};

        // 字典选中
        $rootScope.metaSearch = function(node){
            $scope.setMeta("metadata",node.id);
        };

    	$scope.setMetaId = function(fn){
    		if($scope.metaId==null){
    			$.messager.alert("系统提示","请选择一条元数据！");
				return false;
    		}

    		$rootScope[fn].editRow.mid = $scope.metaId;
    		return true;
    	};

        $rootScope.metaFilter = function(fn,data){
            var fo = $rootScope[fn];
            var toItem = function(e){
                if(fo.valueField!='id'){
                    e.id = e[fo.valueField];
                }

                if(fo.textField!='text'){
                    e.text = e[fo.textField];
                }

                if(fo.showCode && e.text!=e.id){
                    e.text += "("+e.id+")";
                }

                if(fo.leafField==null || fo.leafField==''){
                    // 没有配置子节点字段的，默认全部为子节点
                    e.state = 'open';
                }else{
                    if(e[fo.leafField]==true){
                        e.state = 'open';
                    }else{
                        e.state = 'closed';
                    }
                }
            }

            var toItems = function(es){

                var ri = [];
                es.forEach(function(e){
                    if(e.info && e.info=='2'){
                        ri.push(e);
                    }
                });
                ri.forEach(function(ei){
                    es.remove(ei);
                });

                es.forEach(function(e){
                    toItem(e);
                    var children = e.children;
                    if(children && children.length>0){
                        toItems(children);
                    }
                });
            }

            toItems(data);
        };

	}]);
});